package com.diana.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

@Component
public class AliPayUtils {
    private static final Logger log = LoggerFactory.getLogger(AliPayUtils.class);

    @Value("${alipay.server}")
    private String SERVER;
    @Value("${alipay.app_id}")
    private String APP_ID;
    @Value("${alipay.private_key}")
    private String PRIVATE_KEY;
    @Value("${alipay.public_key}")
    private String PUBLIC_KEY;
    @Value("${alipay.public_key2}")
    private String PUBLIC_KEY2;
    @Value("${alipay.sign_type}")
    private String SIGN_TYPE;
    @Value("${alipay.notify_url}")
    private String NOTIFY_URL;
    @Value("${alipay.return_url}")
    private String RETURN_URL;

    private AlipayClient getAlipayClient(){
        return new DefaultAlipayClient(SERVER,APP_ID,PRIVATE_KEY,"json","utf-8",PUBLIC_KEY2,SIGN_TYPE);
    }

    /**
     * 统一收单下单并支付页面接口
     * @param outTradeNo 唯一商户订单号(订单id)
     * @param totalAmount 订单总金额
     * @param subject 订单标题
     * @param body 订单描述
     * @return
     */
    public String tradePagePay(String outTradeNo,String totalAmount,String subject,String body){
        AlipayClient alipayClient = getAlipayClient();
        String product_code = "FAST_INSTANT_TRADE_PAY";
        JSONObject bizContent = new JSONObject();
        //必填参数
        bizContent.put("product_code",product_code);
        bizContent.put("out_trade_no",outTradeNo);
        bizContent.put("total_amount",totalAmount);
        bizContent.put("subject",subject);
        bizContent.put("body",body);
        //商品详情
        JSONObject detail = new JSONObject();
        detail.put("goods_id","G00001");
        detail.put("goods_name","ipad");
        detail.put("quantity","1");
        detail.put("price","2000");
        JSONArray goods_detail = new JSONArray();
        goods_detail.add(detail);

        bizContent.put("goods_detail",goods_detail);
        //自定义参数
        JSONObject passback_params = new JSONObject();
        passback_params.put("test","测试自定义参数");
        try {
            bizContent.put("passback_params", URLEncoder.encode(passback_params.toJSONString(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.info("参数格式转换异常:{}",e);
        }

        AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
        alipayTradePagePayRequest.setBizContent(bizContent.toJSONString());
        alipayTradePagePayRequest.setNotifyUrl(NOTIFY_URL);
        alipayTradePagePayRequest.setReturnUrl(RETURN_URL);
        String result = "";
        try {
            result = alipayClient.pageExecute(alipayTradePagePayRequest).getBody();
        } catch (AlipayApiException e) {
            log.info("支付异常:{}",e);
        }
        return result;
    }

    /**
     * 支付宝回调验证
     * @param map
     * @return
     */
    public boolean notifyCheck(Map<String,String> map){
        boolean check = false;
        try {
            check = AlipaySignature.rsaCheckV1(map, PUBLIC_KEY2, "utf-8", SIGN_TYPE);
        } catch (AlipayApiException e) {
            log.info("支付宝回调异常:{}",e);
        }
        return check;
    }

    /**
     *
     * @param outRequestNo
     * @param outTradeNo
     * @param refundAmount
     * @param refundReason
     * @param operatorId
     * @return
     */
    public String refund(String outRequestNo,String outTradeNo,String refundAmount,String refundReason,String operatorId){
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",outTradeNo);
        bizContent.put("refund_amount",refundAmount);
        bizContent.put("out_request_no",outRequestNo);
        bizContent.put("refund_reason",refundReason);
        bizContent.put("operator_id",operatorId);
        request.setBizContent(bizContent.toJSONString());
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            boolean success = response.isSuccess();
            if (success){
                return Utils.message("0000","退款成功",null);
            }
            String subCode = response.getSubCode();
            String subMsg = response.getSubMsg();
            String msg = subCode+":"+subMsg;
            log.info("alipay退款失败:{}",msg);
            return Utils.message("0001",subMsg,null);
        } catch (AlipayApiException e) {
            log.error("alipay退款异常:{}",e);
            return Utils.message("0001","退款异常",null);
        }
    }
}
